<template>
    <div>
        <div id="map" class="map-container"></div>
        <div class="anni">
            <button @click="qidian(0)">添加起点</button>
            <button @click="qidian(1)">添加终点</button>
            <button @click="Calculateroute">计算路线</button>
            <button @click="luwangsuanfa">路网算法</button>
            <button @click="luwnag">绘制路网</button>
        </div>
    </div>
</template>
<script lang="ts">
// 定义组件名称
import { defineComponent } from "vue";
export default defineComponent({
    // 定义组件tag标签
    name: "initMap",
    // 定义组件label，首页使用
    labelName: "初始化地图",
    componentIndex: 1
});
</script>
<script setup lang="ts">
import 'leaflet/dist/leaflet.css'
import { onMounted } from "vue";
import L from "leaflet";
import imgUrl from '../../static/1750409744743.png'
import proj4 from 'proj4'
import * as turf from '@turf/turf'


const data = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "background",
            "properties": {},
            'laben': "",
            "fillColor": '#CCC',
            "geometry": {
                "coordinates": [
                    [
                        [
                            14.358300091245923,
                            29.27427349007273
                        ],
                        [
                            14.358300091245923,
                            29.08922655870282
                        ],
                        [
                            14.619686956957935,
                            29.08922655870282
                        ],
                        [
                            14.619686956957935,
                            29.27427349007273
                        ],
                        [
                            14.358300091245923,
                            29.27427349007273
                        ]
                    ]
                ],
                "type": "Polygon"
            },
            "id": 0
        },
        {
            "type": "Feature",
            "properties": {},
            'laben': "茶白道",
            "fillColor": getRandomColor(),
            "geometry": {
                "coordinates": [
                    [
                        [
                            14.411367686388019,
                            29.235836602562912
                        ],
                        [
                            14.419166435360438,
                            29.21568022866255
                        ],
                        [
                            14.43746322360792,
                            29.213062697090166
                        ],
                        [
                            14.461763043384764,
                            29.245246898052173
                        ],
                        [
                            14.411367686388019,
                            29.235836602562912
                        ]
                    ]
                ],
                "type": "Polygon"
            }
        },
        {
            "type": "Feature",
            "properties": {},
            'laben': "瑞星",
            "fillColor": getRandomColor(),
            "geometry": {
                "coordinates": [
                    [
                        [
                            14.54146336420203,
                            29.24933471511747
                        ],
                        [
                            14.540557210130856,
                            29.219767706315253
                        ],
                        [
                            14.600250048519655,
                            29.220833743176442
                        ],
                        [
                            14.58738044491244,
                            29.248851414253323
                        ],
                        [
                            14.55706442234819,
                            29.25405784346964
                        ],
                        [
                            14.54146336420203,
                            29.24933471511747
                        ]
                    ]
                ],
                "type": "Polygon"
            }
        },
        {
            "type": "Feature",
            "properties": {},
            'laben': "沪上阿姨",
            "fillColor": getRandomColor(),
            "geometry": {
                "coordinates": [
                    [
                        [
                            14.391768903271924,
                            29.15197041460388
                        ],
                        [
                            14.38431120436195,
                            29.111415613323317
                        ],
                        [
                            14.440334522819484,
                            29.112974040937303
                        ],
                        [
                            14.462804259636272,
                            29.157201545222463
                        ],
                        [
                            14.414573502822947,
                            29.151981712579627
                        ],
                        [
                            14.391768903271924,
                            29.15197041460388
                        ]
                    ]
                ],
                "type": "Polygon"
            },
            "id": 3
        },
        {
            "type": "Feature",
            "properties": {},
            "laben": "蜜雪冰城",
            "fillColor": getRandomColor(),
            "geometry": {
                "coordinates": [
                    [
                        [
                            14.52213683445899,
                            29.15460187591745
                        ],
                        [
                            14.53165538802756,
                            29.113843469491925
                        ],
                        [
                            14.577168348892286,
                            29.115188655000665
                        ],
                        [
                            14.58286672177104,
                            29.153654451211395
                        ],
                        [
                            14.581084733790135,
                            29.160976355397054
                        ],
                        [
                            14.52213683445899,
                            29.15460187591745
                        ]
                    ]
                ],
                "type": "Polygon"
            }
        }
    ]
}

let map: L.Map | null = null;


const img = new Image()
let mapGroup = null


onMounted(() => {
    // map = initMap();
    initMap()
    drawMap()
});


const marker = []

const dingdian = [
    [
        14.525762398955914,
        29.13162231445313
    ],
    [
        14.453631047367033,
        29.12956237792969
    ],
    [
        14.53772661864954,
        29.230155944824222
    ],
    [
        14.450306456779463,
        29.227066040039066
    ],
    [
        14.36584521690171,
        29.185180664062504
    ]
]


/**
 * Todo 初始化地图
 */
const initMap = () => {
    // 初始化地图实例，设置中心坐标和缩放级别
    // let map: L.Map = L.map("map").setView([39.90002, 116.46], 10);
    // 天地图key
    const mapKey = "37d883978b54bc12f58d30492062d574";

    // L.CRS.Simple.transformation = new L.transformation(1, 0, 1, 0)
    map = L.map('map', {
        center: [14.497843369744567, 29.187240600585938],
        // crs: L.CRS.Simple,
        zoom: 12,
        zoomControl: false,
        attributionControl: false
    })

    mapGroup = new L.LayerGroup()



    // const clipRegion = L.polygon([[31.2, 121.4], [31.2, 121.6], [31.0, 121.6]]);

    // 添加底图瓦片层（以天地图为例）
    // L.tileLayer(
    //     imgUrl,
    //     {
    //         maxZoom: 19,
    //         // 子域名
    //         subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
    //         clipRegionEnabled: true, // 启用裁剪
    //         clipRegion: clipRegion, // 添加裁剪区域
    //     }
    // ).addTo(map);

    uni.showLoading({
        title: '加载中',
        mask: true
    })


    // L.tileLayer(
    //     `http://t{s}.tianditu.gov.cn/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=w&TileMatrix={z}&TileRow={y}&TileCol={x}&style=default&format=tiles&tk=${mapKey}`,
    //     {
    //         maxZoom: 19,
    //         // 子域名
    //         subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"]
    //     }
    // ).addTo(map);

    // return map;
};


function getRandomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function drawMap() {
    // img.src = imgUrl
    // // 图片导入后操作
    // img.onload = () => {
    //     // 设定图片像素范围为坐标范围
    //     const w = img.width
    //     const h = img.height
    //     const bounds = [[0, 0], [h, w]]
    //     const basicMap = L.imageOverlay(imgUrl, bounds)
    //     mapGroup.addLayer(basicMap)
    //     map.addLayer(mapGroup)
    // }






    for (let index = 0; index < data.features.length; index++) {
        const element = data.features[index].geometry
        console.log(element, '我才是')

        var geometry = new L.Polygon(element.coordinates, { color: '#efe3d6', fillColor: data.features[index].fillColor, opacity: 1, fillOpacity: 1, smoothFactor: 1 })
        // label = '楼梯'


        // 自定义提示框和要素合起来使用
        const markerTooltip = L.tooltip({
            // 提示框内容，主体还是对应的html的内容
            content: `<div>${data.features[index].laben}<div>`,
            // 是否始终显示提示工具，默认为 false（仅在鼠标悬停时显示）
            permanent: true,
            // 提示工具是否可交互，默认为 false
            interactive: false,
            // 提示工具的方向（'top', 'right', 'bottom', 'left', 'center' 或 'auto'），默认为 'auto'
            direction: 'auto',
            // 提示工具相对于目标的偏移量，默认为 [0, 0]       
            offset: [0, 0],
            // 提示工具的透明度，默认为 0.9     
            opacity: 0.9,
            // 提示工具是否跟随鼠标移动，默认为 false           
            sticky: false,
            className: "custom-tooltip" // 自定义 CSS 类名
        });


        if (data.features[index].type == "background") {
            geometry.addTo(map)
        } else {
            geometry.addTo(map).bindTooltip(markerTooltip).openTooltip();
        }



        // map.addLayer(geometry)

        // var geometry = new L.DivOverlay(element.coordinates[0]);

        // map.addLayer(geometry)


        console.log(geometry, '我是geometry数据呢')

    }

    initMao()

    // squareGrid.features.forEach(item => {
    //     var geometrys = new L.Polygon(item.geometry.coordinates, { color: 'red', fillColor: 'red', opacity: 0.1, fillOpacity: 0, smoothFactor: 1 })
    //     geometrys.addTo(map)
    // })

    // setTimeout(() => {
    //     map.clearLayers(geometrys)
    //     const element = squareGrid.features[20];
    //     var geometrysoppad = new L.Polygon(scaledPoly.geometry.coordinates, { color: 'yellow', fillColor: 'yellow', opacity: 0.1, fillOpacity: 0, smoothFactor: 1 })
    //     geometrysoppad.addTo(map)
    // }, 3000);



    // for (let index = 0; index < squareGrid.features.length; index++) {

    //     // // const element = squareGrid.features[index]
    //     if (index == 20) {
    //         const element = squareGrid.features[index];
    //         console.log(element, '我渲染了')
    //         // const polygon = squareGrid.features[index]
    //         // console.log(polygon, '我在循环中')
    //         var geometrysoppad = new L.Polygon(element.geometry, { color: 'red', fillColor: 'red', opacity: 0.1, fillOpacity: 0, smoothFactor: 1 })
    //         geometrysoppad.addTo(map)
    //     }
    //     // const polygon = squareGrid.features[index]
    //     // // console.log(polygon, '我在循环中')
    //     // var geometrysoppad = new L.Polygon(element.geometry.coordinates, { color: 'red', fillColor: 'red', opacity: 0.1, fillOpacity: 0, smoothFactor: 1 })
    //     // geometrysoppad.addTo(map)

    // }


    // let startXy = [];//起点所在的网格序号
    // let endXy = [];//终点所在的网格序号


    // //计算每行有多少个网格（为了计算每个网格在整体网格中的序号（供A*算法使用））
    // let columnCount = Math.floor(
    //     turf.distance(
    //         turf.point([enveloped[0], enveloped[1]]),
    //         turf.point([enveloped[0], enveloped[3]])
    //     ) / gridSize
    // );

    // console.log(columnCount, '我计算一下没列有多少个网格')

    // let y = Math.floor(6462 / columnCount)
    // // let x = (y + 1) * columnCount - 6460 - 1;

    // let x = 6528 % columnCount - 1


    // console.log(x, y, columnCount, '我在第几行')
    let count = 0;

    // 判断覆盖物是否在这个多边形里面
    // for (let index = 1; index < data.features.length; index++) {
    //     const element = data.features[index]
    //     console.log(element, '覆盖物')
    //     // // 创建矩形
    //     // let poly = turf.polygon(data.features[0].geometry.coordinates);
    // }


    // for (let index = 0; index < squareGrid.features.length; index++) {
    //     // const element = squareGrid.features[index];

    //     const polygon = squareGrid.features[count]

    //     let center = turf.centroid(polygon);


    //     //计算每个网格的横纵向序号（供A*算法使用）
    //     // let x = Math.floor(index / columnCount);
    //     // let y = (x + 1) * columnCount - index - 1;

    //     let x = Math.floor(count / columnCount);
    //     let y = (x + 1) * columnCount - count - 1;

    //     // let currentGrid = squareGrid.features[count];
    //     // currentGrid.properties = {
    //     //     center: center.geometry.coordinates,//中心点
    //     //     id: `${x}-${y}`,
    //     //     x: x,//横向序号
    //     //     y: y,//纵向序号
    //     // };

    //     if (turf.booleanPointInPolygon(turf.point(startPoit), polygon)) {
    //         console.log('我是起点我在这个多边形内', polygon, turf.point(startPoit), index, columnCount,)
    //     }

    //     if (turf.booleanPointInPolygon(turf.point(endPoit), polygon)) {
    //         console.log('我是终点我在这个多边形内', index, columnCount,)
    //     }

    //     //计算起点和终点的二维xy坐标(turf.booleanPointInPolygon计算点是否在多边形内)
    //     if (!startXy.length && turf.booleanPointInPolygon(turf.point(startPoit), polygon)) {
    //         startXy = { x, y };
    //     }
    //     if (!endXy.length && turf.booleanPointInPolygon(turf.point(endPoit), polygon)) {
    //         endXy = { x, y };
    //     }
    //     count += 1;//count+1开始计算下一个网格的相关属性
    //     // console.log(count, '我循环了多变我看看')
    //     if (count == 20) {
    //         console.log('我等于20了')
    //         // 添加所有的网格
    //         var geoPDPA = new L.Polygon(polygon.geometry.coordinates, { color: 'yellow', fillColor: 'yellow', opacity: 0.1, fillOpacity: 0, smoothFactor: 1 })
    //         console.log(geoPDPA, '我是map')
    //         geoPDPA.addTo(map)
    //     }
    // }

    // console.log("起点", startXy, '结束点', endXy)

    // console.log(squareGrid.features, '我笑死了')


    // // 计算起点和终点
    // if (!startXy.length && turf.booleanPointInPolygon(turf.point(start), polygon)) {
    //     startXy = { x, y };
    // }


    // console.log(columnCount, '我凶死了')



    // let allList = []; //所有网格
    // let openList = []; //待计算的网格
    // squareGrid.features.forEach(({ geometry: { coordinates }, properties }) => {
    //     let obj = {
    //         x: properties.x,
    //         y: properties.y,
    //         id: properties.id,
    //         center: properties.center,
    //         slope: properties.slope,
    //         h: Math.sqrt(
    //             Math.pow(properties.x - endXy.x, 2) +
    //             Math.pow(properties.y - endXy.y, 2)
    //         ), //当前网格和终点距为未来预期代价
    //         g: null, //当前网格和起点距离为历史代价
    //         f: null,
    //         parentId: null,
    //         coordinates: coordinates[0].map((item) => [item[0], item[1]]),
    //     };

    //     if (properties.slope > maxSlope) {
    //         obj.isInCloseList = 1; //障碍物就关闭，后面不再对该网格进行计算
    //     } else {
    //         obj.isInOpenList = 0; //该网格为待计算网格
    //     }
    //     allList.push(obj);
    // });

    // console.log(allList, '我是所有的网格')



    console.log(data.features, '我是data数据呢')

}

// 用来存放网格
let squareGrid = []
let columnCount = 0

function initMao() {
    // 初始化地图
    const genda = data.features[0].geometry.coordinates[0]

    // const startPoit = [14.598202469575067, 29.117889404296875]

    // // 添加起点
    // var startMarker = L.marker(startPoit).addTo(map);
    // startMarker.addTo(map)

    // // 添加终点
    // const endPoit = [14.392783179432298, 29.215393066406254]

    // var endMarker = L.marker(endPoit).addTo(map);

    // endMarker.addTo(map)


    const start = genda[0]
    const end = genda[3]



    let minLng = Math.min(start[0], end[0]);
    let maxLng = Math.max(start[0], end[0]);
    let maxLat = Math.max(start[1], end[1]);
    let minLat = Math.min(start[1], end[1]);


    // // 创建矩形
    let poly = turf.polygon(data.features[0].geometry.coordinates);

    //将矩形扩大5倍（借助turf.js）
    let scaledPoly = turf.transformScale(poly, 1);

    // console.log(scaledPoly.geometry.coordinates[0].flat(), '我才是坐标系')

    var geometrys = new L.Polygon(scaledPoly.geometry.coordinates, { color: 'red', fillColor: 'red', opacity: 1, fillOpacity: 0, smoothFactor: 1 })

    geometrys.addTo(map)

    //计算扩大后的边界
    let enveloped = turf.envelope(scaledPoly).bbox;
    //指定网格大小
    const gridSize = 0.3;
    //划分为网格
    squareGrid = turf.squareGrid(enveloped, gridSize);

    console.log(squareGrid.features, '我才是网格呢')

    // 添加所有的网格
    // squareGrid.features.forEach(item => {
    //     var geometrysins = new L.Polygon(item.geometry.coordinates, { color: 'red', fillColor: 'red', opacity: 0.1, fillOpacity: 0, smoothFactor: 1 })
    //     geometrysins.addTo(map)
    // })

    COVER()

    // setTimeout(() => {
    //     squareGrid.features.forEach(item => {
    //         var geometrysins = new L.Polygon(item.geometry.coordinates, { color: 'yellow', fillColor: 'yellow', opacity: 0.1, fillOpacity: 0, smoothFactor: 1 })
    //         geometrysins.addTo(map)
    //     })
    // }, 3000);

    // let startXy = [];//起点所在的网格序号
    // let endXy = [];//终点所在的网格序号


    //计算每行有多少个网格（为了计算每个网格在整体网格中的序号（供A*算法使用））
    columnCount = Math.floor(
        turf.distance(
            turf.point([enveloped[0], enveloped[1]]),
            turf.point([enveloped[0], enveloped[3]])
        ) / gridSize
    );

    console.log(columnCount, '我计算一下有多少列')

    let y = Math.floor(6462 / columnCount)
    let x = (y + 1) * columnCount - 6460 - 1;

    console.log(x, y, columnCount, '我在第几行')


    let count = 0

    // setTimeout(() => {
    console.log(fugaiewu, '我笑死了呢')
    for (let index = 0; index < squareGrid.features.length; index++) {
        // const element = squareGrid.features[index];

        const polygon = squareGrid.features[count]

        let center = turf.centroid(polygon);


        //计算每个网格的横纵向序号（供A*算法使用）
        // let x = Math.floor(index / columnCount);
        // let y = (x + 1) * columnCount - index - 1;

        let x = Math.floor(count / columnCount);
        let y = (x + 1) * columnCount - count - 1;

        let slope = false


        for (let i = 0; i < fugaiewu.length; i++) {
            const element = fugaiewu[i];
            // console.log(center, '我看看覆盖物')
            // console.log(element, '我看看覆盖物')
            if (turf.booleanPointInPolygon(turf.point(center.geometry.coordinates), element)) {
                slope = true
                // var geometrysins = new L.Polygon(element.geometry.coordinates, { color: '#0fd70f', fillColor: '#0fd70f', opacity: 1, fillOpacity: 0, smoothFactor: 1 })
                // geometrysins.addTo(map)
                // console.log('我在覆盖物里面', center.geometry.coordinates, element)
            }
        }

        // const slpe = turf.booleanPointInPolygon(turf.point(startPoit), polygon)
        // console.log(x, y, '我在第几行第几列')
        let currentGrid = squareGrid.features[count];
        currentGrid.properties = {
            slope: slope, //是否有障碍物
            center: center.geometry.coordinates,//中心点
            id: `${x}-${y}`,
            x: x,//横向序号
            y: y,//纵向序号
        };


        // if (turf.booleanPointInPolygon(turf.point(startPoit), polygon)) {
        //     console.log('我是起点我在这个多边形内', polygon, turf.point(startPoit), index, columnCount,)
        // }

        // if (turf.booleanPointInPolygon(turf.point(endPoit), polygon)) {
        //     console.log('我是终点我在这个多边形内', index, columnCount,)
        // }

        //计算起点和终点的二维xy坐标(turf.booleanPointInPolygon计算点是否在多边形内)
        // if (!startXy.length && turf.booleanPointInPolygon(turf.point(startPoit), polygon)) {
        //     startXy = { x, y };
        //     var geometrysins = new L.Polygon(polygon.geometry.coordinates, { color: '#0fd70f', fillColor: '#0fd70f', opacity: 1, fillOpacity: 0, smoothFactor: 1 })
        //     geometrysins.addTo(map)
        // }
        // if (!endXy.length && turf.booleanPointInPolygon(turf.point(endPoit), polygon)) {
        //     endXy = { x, y };
        //     var geometrysins = new L.Polygon(polygon.geometry.coordinates, { color: '#0fd70f', fillColor: '#0fd70f', opacity: 1, fillOpacity: 0, smoothFactor: 1 })
        //     geometrysins.addTo(map)
        // }
        count += 1;
        // console.log(count, '我循环了多变我看看')
        // if (index < 2) {
        //     // console.log('我等于20了', polygon.geometry.coordinates)
        //     // 添加所有的网格
        //     var geometrysins = new L.Polygon(polygon.geometry.coordinates, { color: '#0fd70f', fillColor: '#0fd70f', opacity: 1, fillOpacity: 0, smoothFactor: 1 })
        //     geometrysins.addTo(map)
        // }
    }
    // Pathfinding(startXy, endXy)
    // }, 3000);
}

const fugaiewu = []
// 根据覆盖物生成网格
function COVER() {


    // 判断这个覆盖物是否在网格里面
    for (let index = 1; index < data.features.length; index++) {
        const element = data.features[index];
        console.log(element.geometry.coordinates, '我是覆盖物网格')
        // // 创建矩形



        let poly = turf.polygon(element.geometry.coordinates);


        //将矩形扩大5倍（借助turf.js）
        let scaledPoly = turf.transformScale(poly, 1.1);
        // console.log(scaledPoly.geometry.coordinates[0].flat(), '我才是坐标系')
        // var geometrys = new L.Polygon(scaledPoly.geometry.coordinates, { color: 'red', fillColor: 'red', opacity: 1, fillOpacity: 0, smoothFactor: 1 })
        // geometrys.addTo(map)
        //计算扩大后的边界
        let enveloped = turf.envelope(scaledPoly).bbox;
        //指定网格大小
        const gridSize = 0.3;
        //划分为网格
        let squareGrid = turf.squareGrid(enveloped, gridSize, { units: "miles" });

        console.log(squareGrid.features, '我才是网格呢')

        // 添加所有的网格
        squareGrid.features.forEach(item => {
            fugaiewu.push(item)
            // var geometrysins = new L.Polygon(item.geometry.coordinates, { color: 'yellow', fillColor: 'yellow', opacity: 0.5, fillOpacity: 0.3, smoothFactor: 1 })
            // geometrysins.addTo(map)
        })
    }

    uni.hideLoading()


    // // 初始化地图
    // const genda = data.features[0].geometry.coordinates[0]

    // const startPoit = [14.598202469575067, 29.117889404296875]

    // // 添加起点
    // var startMarker = L.marker(startPoit).addTo(map);
    // startMarker.addTo(map)

    // // 添加终点
    // const endPoit = [14.392783179432298, 29.215393066406254]

    // var endMarker = L.marker(endPoit).addTo(map);

    // endMarker.addTo(map)


    // const start = genda[0]
    // const end = genda[3]


    // // // 创建矩形
    // let poly = turf.polygon(data.features[0].geometry.coordinates);

    // //将矩形扩大5倍（借助turf.js）
    // let scaledPoly = turf.transformScale(poly, 1);

    // // console.log(scaledPoly.geometry.coordinates[0].flat(), '我才是坐标系')

    // var geometrys = new L.Polygon(scaledPoly.geometry.coordinates, { color: 'red', fillColor: 'red', opacity: 1, fillOpacity: 0, smoothFactor: 1 })

    // geometrys.addTo(map)

    // //计算扩大后的边界
    // let enveloped = turf.envelope(scaledPoly).bbox;
    // //指定网格大小
    // const gridSize = 0.3;
    // //划分为网格
    // let squareGrid = turf.squareGrid(enveloped, gridSize);

    // console.log(squareGrid.features, '我才是网格呢')

    // // 添加所有的网格
    // squareGrid.features.forEach(item => {
    //     var geometrysins = new L.Polygon(item.geometry.coordinates, { color: 'red', fillColor: 'red', opacity: 0.1, fillOpacity: 0, smoothFactor: 1 })
    //     geometrysins.addTo(map)
    // })

}


// 使用a*算法寻路
function Pathfinding(startXy, endXy) {

    const maxSlope = 25;//可以通过的最大坡度
    let allList = []; //所有网格
    let openList = []; //待计算的网格
    squareGrid.features.forEach(({ geometry: { coordinates }, properties }) => {
        let obj = {
            x: properties.x,
            y: properties.y,
            id: properties.id,
            center: properties.center,
            slope: properties.slope,
            h: Math.sqrt(
                Math.pow(properties.x - endXy.x, 2) +
                Math.pow(properties.y - endXy.y, 2)
            ), //当前网格和终点距为未来预期代价
            g: null, //当前网格和起点距离为历史代价
            f: null,
            parentId: null,
            coordinates: coordinates[0].map((item) => [item[0], item[1]]),
        };

        // > maxSlope
        // 如果是障碍物
        if (properties.slope) {
            obj.isInCloseList = 1; //障碍物就关闭，后面不再对该网格进行计算
        } else {
            obj.isInOpenList = 0; //该网格为待计算网格
        }
        allList.push(obj);
    });
    let startNode = allList.find(
        (item) => item.x == startXy.x && item.y == startXy.y
    );
    startNode.g = 0;
    startNode.isInOpenList = 1;
    //计算好起点的代价后将它插入到openList中
    openList.push(startNode);
    let endNode = {};

    while (openList.length) {
        //根据代价逆序排序，从openList中获取到代价最小的网格（如果有多个代价相同的点，优先选择 g 值（历史代价）较小的网格，因为这更有可能导向最短路径。）
        let sortedByF = openList.sort((a, b) => a.f - b.f);
        let minFNodes = sortedByF.filter((item) => item.f == sortedByF[0].f);
        let nodeCurrent = minFNodes.sort((a, b) => a.g - b.g)[0];
        //获取代价最小的网格周围的网格
        let childUp = allList.find(
            (item) => item.x == nodeCurrent.x && item.y == nodeCurrent.y - 1
        );
        let childRight = allList.find(
            (item) => item.x == nodeCurrent.x + 1 && item.y == nodeCurrent.y
        );
        let childDown = allList.find(
            (item) => item.x == nodeCurrent.x && item.y == nodeCurrent.y + 1
        );
        let childLeft = allList.find(
            (item) => item.x == nodeCurrent.x - 1 && item.y == nodeCurrent.y
        );
        let childList = [childUp, childRight, childDown, childLeft];
        //只有当左边和上边不全是障碍物，才能走左上的网格
        if (!childUp?.isInCloseList || !childLeft?.isInCloseList) {
            let childLeftUp = allList.find(
                (item) => item.x == nodeCurrent.x - 1 && item.y == nodeCurrent.y - 1
            );
            childList.push(childLeftUp);
        }
        //只有当右边和上边不全是障碍物，才能走右上的网格
        if (!childUp?.isInCloseList || !childRight?.isInCloseList) {
            let childRightUp = allList.find(
                (item) => item.x == nodeCurrent.x + 1 && item.y == nodeCurrent.y - 1
            );
            childList.push(childRightUp);
        }
        //只有当右边和下边不全是障碍物，才能走右下的网格
        if (!childDown?.isInCloseList || !childRight?.isInCloseList) {
            let childRightDown = allList.find(
                (item) => item.x == nodeCurrent.x + 1 && item.y == nodeCurrent.y + 1
            );
            childList.push(childRightDown);
        }
        //只有当左边和下边不全是障碍物，才能走左下的网格
        if (!childDown?.isInCloseList || !childLeft?.isInCloseList) {
            let childLeftDown = allList.find(
                (item) => item.x == nodeCurrent.x - 1 && item.y == nodeCurrent.y + 1
            );
            childList.push(childLeftDown);
        }
        //遍历周围网格
        for (let i = 0; i < childList.length; i++) {
            let child = childList[i];
            if (!child || child.isInCloseList == 1) {
                //已经关闭，后面不再计算
                continue;
            }
            //计算当前网格到它子网格的距离
            let currentToChild = Math.sqrt(
                Math.pow(nodeCurrent.x - child.x, 2) +
                Math.pow(nodeCurrent.y - child.y, 2)
            );

            if (child.isInOpenList == 0) {
                //从来没有被计算过，现在计算它的代价
                child.parentId = nodeCurrent.id;
                //子网格的历史代价是当前网格历史代价加上当前网格到子网格的距离
                child.g = nodeCurrent.g + currentToChild;
                //子网格的未来期望代价是子网格到终点的距离
                child.h = Math.sqrt(
                    Math.pow(child.x - endXy.x, 2) + Math.pow(child.y - endXy.y, 2)
                );
                //得出最终代价
                child.f = child.g + child.h;
                //设置标记，表明这个子网格已经被计算过至少一次了
                child.isInOpenList = 1;
                openList.push(child); //将这个子网格加入到待计算列表中
            } else if (child.isInOpenList == 1) {
                //这个子网格被计算过
                // 将子网格的父级替换为当前网格重新计算代价
                let g = nodeCurrent.g + currentToChild;
                //如果更换为新父级后代价比以前小，就更新一下
                if (g < child.g) {
                    child.g = g;
                    child.f = child.g + child.h;
                    child.parentId = nodeCurrent.id;
                }
            }
            //找到终点了，赋值后直接跳出
            if (child.x == endXy.x && child.y == endXy.y) {
                endNode = child;

                let roadPath = [];
                //溯源出路线
                let currentNode = endNode;
                while (currentNode) {
                    roadPath.push(currentNode.center);
                    currentNode = allList.find(({ id }) => id == currentNode.parentId);
                }
                let line = turf.lineString(roadPath);
                console.log(roadPath, '我是路线数据呢')


                polyLine = L.polyline(roadPath, { color: 'green' }).addTo(map);

                qi = []
                zhond = []

                break;
            }
        }
        if (endNode.id) {
            break;
        }

        //将当前网格从待计算列表中移除并将它关闭
        let index = openList.findIndex(
            ({ x, y }) => x == nodeCurrent.x && y == nodeCurrent.y
        );
        openList[index].isInCloseList = 1;
        openList.splice(index, 1);
    }
    if (!openList.length && !endNode.id) {
        alert("无路可走");
    }
}


let polyLine = null

// 计算路线
function Calculateroute() {


    console.log(polyLine, '我是线路呢')

    if (polyLine) {
        map.removeLayer(polyLine);
    }



    console.log(qi, zhond, '我是开始和结束')

    let startXy = [];//起点所在的网格序号
    let endXy = [];//终点所在的网格序号

    for (let index = 0; index < squareGrid.features.length; index++) {
        // const element = squareGrid.features[index];
        const polygon = squareGrid.features[index];

        //计算每个网格的横纵向序号（供A*算法使用）
        let x = Math.floor(index / columnCount);
        let y = (x + 1) * columnCount - index - 1;

        //计算起点和终点的二维xy坐标(turf.booleanPointInPolygon计算点是否在多边形内)
        if (!startXy.length && turf.booleanPointInPolygon(turf.point(qi), polygon)) {
            startXy = { x, y };
            var geometrysins = new L.Polygon(polygon.geometry.coordinates, { color: '#0fd70f', fillColor: '#0fd70f', opacity: 1, fillOpacity: 0, smoothFactor: 1 })
            geometrysins.addTo(map)
        }
        if (!endXy.length && turf.booleanPointInPolygon(turf.point(zhond), polygon)) {
            endXy = { x, y };
            var geometrysins = new L.Polygon(polygon.geometry.coordinates, { color: '#0fd70f', fillColor: '#0fd70f', opacity: 1, fillOpacity: 0, smoothFactor: 1 })
            geometrysins.addTo(map)
        }
        // console.log(count, '我循环了多变我看看')
        // if (index < 2) {
        //     // console.log('我等于20了', polygon.geometry.coordinates)
        //     // 添加所有的网格
        //     var geometrysins = new L.Polygon(polygon.geometry.coordinates, { color: '#0fd70f', fillColor: '#0fd70f', opacity: 1, fillOpacity: 0, smoothFactor: 1 })
        //     geometrysins.addTo(map)
        // }
    }


    console.log("起点", startXy, '结束点', endXy)
    // 根据x和y计算出对应的x和y
    Pathfinding(startXy, endXy);
}





let qi = []
let zhond = []

const markers = []

function qidian(params) {
    map.removeEventListener('click', handjiant);
    map.on('click', handjiant);
}

function handjiant(e) {
    const point = [e.latlng.lat, e.latlng.lng]

    var meMarker = L.marker([point[0], point[1]]).addTo(map);
    if (qi.length === 0) {
        qi = point
    } else {
        zhond = point
    }
    markers.push(meMarker);
}

// 路网节点数据
const roadNetwork = {
    nodes: {
        'A': {
            latlng: [
                14.598202469575067,
                29.12509918212891
            ], neighbors: ['B', 'C']
        },
        'B': {
            latlng: [
                14.59488005156597,
                29.168701171875004
            ], neighbors: ['C', 'E']
        },
        'C': {
            latlng: [
                14.548028622070289,
                29.164237976074222
            ], neighbors: ['F', 'D']
        },
        'D': {
            latlng: [
                14.41739032942046,
                29.161148071289066
            ], neighbors: ['F', 'G']
        },
        'E': {
            latlng: [
                14.557997845129691,
                29.21367645263672
            ], neighbors: ['B', 'F']
        },
        'F': {
            latlng: [
                14.42470544493101,
                29.206809997558597
            ], neighbors: ['D', 'G', 'E', 'C']
        },
        'G': {
            latlng: [
                14.37316202169223,
                29.187927246093754
            ], neighbors: ['D', 'F']
        },

    },
    edges: [
        { from: 'A', to: 'B', weight: 5 },
        { from: 'B', to: 'C', weight: 5 },
        { from: 'B', to: 'E', weight: 6 },
        { from: 'C', to: 'D', weight: 10 },
        { from: 'C', to: 'F', weight: 10 },
        { from: 'D', to: 'G', weight: 6 },
        { from: 'D', to: 'F', weight: 5 },
        { from: 'G', to: 'F', weight: 7 },
        { from: 'F', to: 'E', weight: 10 },
    ]
};

// 路径可视化
let routeLayer = null;

function luwangsuanfa() {
    Object.entries(roadNetwork.nodes).forEach(([id, latlng]) => {
        const element = latlng.latlng
        var circle = L.circle(element, {
            color: 'red',
            fillColor: '#f03',
            fillOpacity: 0.5,
            radius: 200
        }).addTo(map);
        const markerTooltip = L.tooltip({
            // 提示框内容，主体还是对应的html的内容
            content: `<div>${id}<div>`,
            // 是否始终显示提示工具，默认为 false（仅在鼠标悬停时显示）
            permanent: true,
            // 提示工具是否可交互，默认为 false
            interactive: false,
            // 提示工具的方向（'top', 'right', 'bottom', 'left', 'center' 或 'auto'），默认为 'auto'
            direction: 'auto',
            // 提示工具相对于目标的偏移量，默认为 [0, 0]       
            offset: [0, 0],
            // 提示工具的透明度，默认为 0.9     
            opacity: 0.9,
            // 提示工具是否跟随鼠标移动，默认为 false           
            sticky: false,
            className: "custom-tooltip" // 自定义 CSS 类名
        });
        circle.addTo(map).bindTooltip(markerTooltip).openTooltip();
    });

    // for (let index = 0; index < roadNetwork.edges.length; index++) {
    //     const element = roadNetwork.nodes[roadNetwork.edges[index].from].latlng

    //     console.log(element, '我是路网的节点呢')
    //     var circle = L.circle(element, {
    //         color: 'red',
    //         fillColor: '#f03',
    //         fillOpacity: 0.5,
    //         radius: 200
    //     }).addTo(map);

    //     const markerTooltip = L.tooltip({
    //         // 提示框内容，主体还是对应的html的内容
    //         content: `<div>${roadNetwork.edges[index].from}<div>`,
    //         // 是否始终显示提示工具，默认为 false（仅在鼠标悬停时显示）
    //         permanent: true,
    //         // 提示工具是否可交互，默认为 false
    //         interactive: false,
    //         // 提示工具的方向（'top', 'right', 'bottom', 'left', 'center' 或 'auto'），默认为 'auto'
    //         direction: 'auto',
    //         // 提示工具相对于目标的偏移量，默认为 [0, 0]       
    //         offset: [0, 0],
    //         // 提示工具的透明度，默认为 0.9     
    //         opacity: 0.9,
    //         // 提示工具是否跟随鼠标移动，默认为 false           
    //         sticky: false,
    //         className: "custom-tooltip" // 自定义 CSS 类名
    //     });


    //     circle.addTo(map).bindTooltip(markerTooltip).openTooltip();

    // }









    const stata = findNearestNode(L.latLng(qi[0], qi[1]));
    const endata = findNearestNode(L.latLng(zhond[0], zhond[1]));
    console.log(stata, endata, '我是起点和终点呢')

    const path = findShortestPath(stata, endata)


    if (routeLayer) map.removeLayer(routeLayer);
    const latlngs = path.map(nodeId => roadNetwork.nodes[nodeId].latlng);

    console.log(latlngs, '我找到了')

    const da = turf.lineString(
        latlngs,
        { name: "line 1" },
    );

    console.log(da, '我是turf的线呢')
    routeLayer = L.polyline(da.geometry.coordinates, { color: 'blue', weight: 5 }).addTo(map);
    // map.fitBounds(routeLayer.getBounds());
}



// 查找距离坐标最近的节点
function findNearestNode(latlng) {
    // console.log(latlng, '我是查找最近的节点呢')
    let minDist = Infinity;
    let nearestNode = null;

    Object.entries(roadNetwork.nodes).forEach(([nodeId, nodeLatLng]) => {
        console.log(latlng, nodeLatLng, '我是节点的坐标呢')
        const dist = map.distance(latlng, nodeLatLng.latlng);
        if (dist < minDist) {
            minDist = dist;
            nearestNode = nodeId;
        }
    });
    return nearestNode;
}

// 路网算法
function findShortestPath(startNode, endNode) {

    const graph = {};
    roadNetwork.edges.forEach(edge => {
        if (!graph[edge.from]) graph[edge.from] = {};
        if (!graph[edge.to]) graph[edge.to] = {};
        graph[edge.from][edge.to] = edge.weight;
        graph[edge.to][edge.from] = edge.weight;
    });

    const distances = {};
    const previous = {};
    const unvisited = new Set(Object.keys(roadNetwork.nodes));

    unvisited.forEach(node => {
        distances[node] = node === startNode ? 0 : Infinity;
        previous[node] = null;
    });

    while (unvisited.size > 0) {
        let current = [...unvisited].reduce((a, b) =>
            distances[a] < distances[b] ? a : b);

        if (current === endNode || distances[current] === Infinity) break;

        Object.entries(graph[current] || {}).forEach(([neighbor, weight]) => {
            const alt = distances[current] + weight;
            if (alt < distances[neighbor]) {
                distances[neighbor] = alt;
                previous[neighbor] = current;
            }
        });

        unvisited.delete(current);
    }

    const path = [];
    let current = endNode;
    while (current) {
        path.unshift(current);
        current = previous[current];
    }
    return path.length > 1 ? path : null;

}


// 我是路网
function luwnag() {

    const pinaa = []

    map.on('click', (e) => {

        const point = [e.latlng.lat, e.latlng.lng]

        var meMarker = L.marker([point[0], point[1]]).addTo(map);

        pinaa.push(point)
        markers.push(meMarker);

        console.log(pinaa, '我是路网的点呢')
    });

}


</script>

<style scoped>
.map-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

.anni {
    position: absolute;
    bottom: 20px;
    right: 20px;
    z-index: 999;

}

button {
    font-size: 20rpx;
}
</style>
